package com.lsc.record.core.order;

import java.util.List;

import javax.annotation.Resource;

import com.lsc.record.core.service.*;
import com.mybatisflex.core.row.Db;

import cn.hutool.core.io.FileUtil;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.lsc.record.config.StoreProp;
import com.lsc.record.core.entity.DmStore;
import com.lsc.record.core.entity.DmType;
import com.lsc.record.core.entity.TableEntity;

import lombok.extern.slf4j.Slf4j;

@Component
@Order(0)
@Slf4j
public class StartCheckDataOrder implements ApplicationRunner {

	@Resource
	private TypeService typeService;
	
	@Resource
	private FormServcie formService;
	
	@Resource
	private StoreService storeService;
	
	@Resource
	private TableQueryServcie tableService;

	@Resource
	private ListViewServcie listViewServcie;
	
	@Resource
	StoreProp storeProp;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		log.info("**********初始数据检查-开始**************");
		
		String sncontent="CREATE SEQUENCE IF NOT EXISTS SN_CONTENT_DATATIKET INCREMENT BY 1 START WITH 0 MINVALUE 0 CYCLE";
		Db.updateBySql(sncontent);
		
		checkStore();
		checkTypeData();
		checkFormData();
		checkListViewData();
		log.info("**********初始数据检查-结束**************");
	}
	
	private void checkStore() {
		if(storeService.count()<1) {
			DmStore store = new DmStore();
			store.setName("store1");
			store.setStoreType("FILEPATH");
			store.setStoreValue(storeProp.getDefaultSavePath());
			storeService.save(store);
			FileUtil.mkdir(storeProp.getDefaultSavePath());
		}
	}
	
	private void checkTypeData() {
		long count = typeService.count();
		if(count>0) {
			return;
		}
		log.info("**********初始化类型数据-开始**************");
		List<TableEntity> tableList = tableService.list(true);
		
		typeService.initType(tableList);
		log.info("**********初始化类型数据-结束**************");
	}
	
	private void checkFormData() {
		long count = formService.count();
		if(count>0) {
			return;
		}
		log.info("**********初始化表单数据-开始**************");
		List<DmType> typeList = typeService.list(true);
		for (DmType type : typeList) {			
			formService.initForm(type);
		}
		log.info("**********初始化表单数据-结束**************");
	}

	private void checkListViewData(){
		log.info("**********初始化列表视图数据-开始**************");
		List<DmType> typeList = typeService.list(true);
		for (DmType type : typeList) {
			listViewServcie.initListView(type);
		}
		log.info("**********初始化列表视图数据-结束**************");
	}
}
